import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, Card, Tabs, Alert, Typography, Space, Divider } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, MobileOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';

const { Title, Text } = Typography;

const LoginPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('login');
  const [loginError, setLoginError] = useState<string | null>(null);
  const [registerError, setRegisterError] = useState<string | null>(null);
  const navigate = useNavigate();
  const { login, register, isAuthenticated } = useAuthStore();
  
  // 如果已经登录，重定向到首页
  if (isAuthenticated) {
    navigate('/');
    return null;
  }
  
  // 处理登录
  const handleLogin = async (values: any) => {
    try {
      setLoginError(null);
      await login(values.username, values.password);
      navigate('/');
    } catch (error) {
      setLoginError('登录失败，请检查用户名和密码');
    }
  };
  
  // 处理注册
  const handleRegister = async (values: any) => {
    try {
      setRegisterError(null);
      await register(values.username, values.email, values.password);
      setActiveTab('login');
    } catch (error) {
      setRegisterError('注册失败，请稍后重试');
    }
  };
  
  return (
    <div style={{ 
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      minHeight: '100vh',
      background: '#f0f2f5'
    }}>
      <Card style={{ width: 400 }}>
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ marginBottom: 8 }}>企业知识库管理平台</Title>
          <Text type="secondary">登录或注册以继续</Text>
        </div>
        
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          centered
          items={[
            {
              key: 'login',
              label: '登录',
              children: (
                <>
                  {loginError && (
                    <Alert 
                      message={loginError} 
                      type="error" 
                      showIcon 
                      style={{ marginBottom: 16 }} 
                    />
                  )}
                  
                  <Form
                    name="login"
                    initialValues={{ remember: true }}
                    onFinish={handleLogin}
                  >
                    <Form.Item
                      name="username"
                      rules={[{ required: true, message: '请输入用户名' }]}
                    >
                      <Input prefix={<UserOutlined />} placeholder="用户名" size="large" />
                    </Form.Item>
                    
                    <Form.Item
                      name="password"
                      rules={[{ required: true, message: '请输入密码' }]}
                    >
                      <Input.Password prefix={<LockOutlined />} placeholder="密码" size="large" />
                    </Form.Item>
                    
                    <Form.Item>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Form.Item name="remember" valuePropName="checked" noStyle>
                          <Checkbox>记住我</Checkbox>
                        </Form.Item>
                        
                        <a href="#">忘记密码?</a>
                      </div>
                    </Form.Item>
                    
                    <Form.Item>
                      <Button type="primary" htmlType="submit" block size="large">
                        登录
                      </Button>
                    </Form.Item>
                  </Form>
                </>
              ),
            },
            {
              key: 'register',
              label: '注册',
              children: (
                <>
                  {registerError && (
                    <Alert 
                      message={registerError} 
                      type="error" 
                      showIcon 
                      style={{ marginBottom: 16 }} 
                    />
                  )}
                  
                  <Form
                    name="register"
                    onFinish={handleRegister}
                  >
                    <Form.Item
                      name="username"
                      rules={[{ required: true, message: '请输入用户名' }]}
                    >
                      <Input prefix={<UserOutlined />} placeholder="用户名" size="large" />
                    </Form.Item>
                    
                    <Form.Item
                      name="email"
                      rules={[
                        { required: true, message: '请输入邮箱地址' },
                        { type: 'email', message: '请输入有效的邮箱地址' }
                      ]}
                    >
                      <Input prefix={<MailOutlined />} placeholder="邮箱" size="large" />
                    </Form.Item>
                    
                    <Form.Item
                      name="password"
                      rules={[
                        { required: true, message: '请输入密码' },
                        { min: 8, message: '密码长度不能少于8个字符' }
                      ]}
                    >
                      <Input.Password prefix={<LockOutlined />} placeholder="密码" size="large" />
                    </Form.Item>
                    
                    <Form.Item
                      name="confirm"
                      dependencies={['password']}
                      rules={[
                        { required: true, message: '请确认密码' },
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!value || getFieldValue('password') === value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(new Error('两次输入的密码不一致'));
                          },
                        }),
                      ]}
                    >
                      <Input.Password prefix={<LockOutlined />} placeholder="确认密码" size="large" />
                    </Form.Item>
                    
                    <Form.Item>
                      <Button type="primary" htmlType="submit" block size="large">
                        注册
                      </Button>
                    </Form.Item>
                  </Form>
                </>
              ),
            },
          ]}
        />
        
        <Divider>第三方登录</Divider>
        
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Space size="large">
            <Button shape="circle" icon={<i className="fab fa-google" />} />
            <Button shape="circle" icon={<i className="fab fa-github" />} />
            <Button shape="circle" icon={<i className="fab fa-weixin" />} />
          </Space>
        </div>
      </Card>
    </div>
  );
};

export default LoginPage; 